<?php
/**
 * Ресурс приложения, инициализирующий навигационные меню. 
 * 
 * @todo Прибить как только XML-меню перенесем в виджеты
 * 
 * @category Phorm
 * @package Application_Resource
 * @name /Phorm/Application/Resource/Navigation.php
 * @copyright phorm.ru
 * @since 06.01.2011
 * @author vladimir@kachalov.net
 */

class Phorm_Application_Resource_Navigation extends Zend_Application_Resource_ResourceAbstract {
	
	/**
	 * Массив контейнеров Zend_Navigation
	 * @var array
	 */
	public $_containers = array();
	
	/**
	 * Инициализация пользовательской сессии
	 *
	 * @return array
	 */
	
	public function init() {
		
		$this->_bootstrap->bootstrap('Usersession');
		$this->_bootstrap->bootstrap('View');

		$acl = new Zend_Acl();
		$role = $this->_bootstrap->Usersession->UserData['roleid'];
		$acl->addRole(new Zend_Acl_Role($role));
		
		$db = $this->_bootstrap->Db;
		
		$select = $db->select()
				-> from('pw_mvc_resources',new Zend_Db_Expr('DISTINCT module,controller'));
		
		foreach ($db->fetchAll($select) as $row) {
			$acl -> add(new Zend_Acl_Resource(join(':',$row)));
		}
		
		foreach ($this->_bootstrap->Usersession->UserData['acl']['mvc'] as $modulename=>$moduledata) {
			foreach ($moduledata as $controllername=>$controllerdata) {
				$acl -> allow($role,$modulename.":".$controllername,array_keys($controllerdata));
			}
		}
		
		Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
	    Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($role);
	    
	    
	    $navigation = $this->_bootstrap->View->navigation();
		
	    $dir = APPLICATION_PATH . '/configs/navigation/';
	    
	    if(is_dir($dir)) {
	    
			$handle = opendir($dir);
			
			while ($module = readdir($handle)) { 
				
				if(is_dir($dir . $module) && !in_array($module,array('.','..'))) {
					
					$files = opendir($dir . $module);
					
					while ($file = readdir($files)) { 
	
						if(preg_match('#^([^\.]+)\.xml$#iu',$file,$fileinfo)) {
							
							$container = new Zend_Navigation(new Zend_Config_Xml($dir . $module . '/' .$file));
							
							$this->_containers[$module][$fileinfo[1]] = array(
								'menu' => $navigation->menu($container)->render(),
								'breadcrumbs' => $navigation->breadcrumbs($container)->render(),
							);
							
						}
					
					}
					
					closedir($files);
				
				}
				
			}
			
			closedir($handle);
		
	    }
		
		$this->_bootstrap->View->assign('Navigation',$this->_containers);
		
		return $this->_containers;
		
	}
	
}